#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
#include <QTcpSocket>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    //1.修改窗口标题
    this->setWindowTitle("服务器");
    //2.创建QTcpServer的实例
    tcpServer = new QTcpServer(this);
    //3.通过信号槽，指定如何处理连接
    connect(tcpServer,&QTcpServer::newConnection,this,&Widget::processConection);
    //4.绑定并监听端口号  一定要确保准备工作充分了，再真正开张营业
    //这个操作得是初始化的最后一步，都是需要把如何处理连接，如何处理请求等都准备好嘞之后，再开始真正绑定端口并监听
    bool ret = tcpServer->listen(QHostAddress::Any,9090);
    if(!ret)
    {
        QMessageBox::critical(this,"服务器启动失败",tcpServer->errorString());
        exit(1);
    }







}

Widget::~Widget()
{
    delete ui;
}

void Widget::processConection()
{
    ui->listWidget->addItem("客户端上线");

    //1.通过tcpserver拿到一个socket对象，通过这个对象和客户端进行通信
    QTcpSocket* clientSocket = tcpServer->nextPendingConnection();
    QString log = "["+clientSocket->peerAddress().toString()+":"+QString::number(clientSocket->peerPort())+"]";

    //2.通过信号槽，来处理客户端发来请求的情况
    connect(clientSocket,&QTcpSocket::readyRead,this,[=](){
        //读取出请求数据，此处readALL返回的是QByteArray,通过赋值转成QString
        QString request = clientSocket->readAll();
        //根据请求处理响应
        const QString& response = process(request);
        //响应写回客户端
        clientSocket->write(response.toUtf8());
        //把上述信息记录到日志中
        QString log = "["+clientSocket->peerAddress().toString()+":"+QString::number(clientSocket->peerPort())+"]"
                +"req:"+",resp:"+response;
        ui->listWidget->addItem(log);

    });

    //3.处理信号槽，来处理客户端断开的情况
    connect(clientSocket,&QTcpSocket::disconnected,this,[=](){
       //把断开连接的信息通过日志显示出来
        QString log = "["+clientSocket->peerAddress().toString()+":"+QString::number(clientSocket->peerPort())+"]客户端下线";
        ui->listWidget->addItem(log);

        //手动释放clientSocket
        //delete  clientSocket;
        clientSocket->deleteLater();

    });
}

QString Widget::process(const QString requset)
{
    return requset;
}

